<template>
  <div class="production-home-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="title">
        <i class="fa fa-industry"></i>
        <span>生产管理首页</span>
      </div>
      <div class="actions">
        <el-button type="primary" @click="createProductionPlan">
          <i class="fa fa-plus"></i> 新增生产计划
        </el-button>
      </div>
    </div>

    <!-- 关键指标卡片 -->
    <el-row :gutter="15" class="kpi-cards">
      <el-col :span="6" v-for="(card, index) in kpiCards" :key="index">
        <div class="kpi-card" :class="card.class">
          <div class="kpi-card-icon">
            <i :class="card.icon"></i>
          </div>
          <div class="kpi-card-content">
            <div class="kpi-card-title">{{ card.title }}</div>
            <div class="kpi-card-value">{{ card.value }}</div>
            <div class="kpi-card-trend">
              <span :class="card.trendClass">
                <i :class="card.trendIcon"></i> {{ card.trend }}
              </span>
              <span class="kpi-card-desc">{{ card.desc }}</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-row :gutter="15" class="main-content">
      <!-- 左侧图表和生产计划 -->
      <el-col :span="16">
        <!-- 生产量与销售趋势图 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">
              <i class="fa fa-bar-chart"></i>
              <span>生产量与销售趋势</span>
            </div>
            <div class="chart-tools">
              <el-radio-group v-model="trendChartPeriod" size="small">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
                <el-radio-button label="quarter">季</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-body">
            <div id="productionSalesTrend" class="chart" style="height: 300px;"></div>
          </div>
        </div>

        <!-- 生产计划进度 -->
        <div class="plan-progress-card">
          <div class="card-header">
            <div class="card-title">
              <i class="fa fa-tasks"></i>
              <span>生产计划进度</span>
            </div>
            <div class="card-tools">
              <el-select v-model="progressFilter" placeholder="全部" size="small">
                <el-option label="全部" value="all"></el-option>
                <el-option label="进行中" value="in-progress"></el-option>
                <el-option label="已完成" value="completed"></el-option>
                <el-option label="延期" value="delayed"></el-option>
              </el-select>
            </div>
          </div>
          <div class="card-body">
            <el-table :data="productionPlans" style="width: 100%" stripe>
              <el-table-column prop="planNo" label="计划编号" width="120"></el-table-column>
              <el-table-column prop="productName" label="产品名称" width="180"></el-table-column>
              <el-table-column prop="planQuantity" label="计划数量" width="100"></el-table-column>
              <el-table-column prop="completedQuantity" label="已完成" width="100"></el-table-column>
              <el-table-column prop="deadlineDate" label="截止日期" width="120"></el-table-column>
              <el-table-column label="进度" min-width="200">
                <template #default="scope">
                  <div class="progress-info">
                    <el-progress 
                      :percentage="scope.row.progressPercentage" 
                      :status="scope.row.progressStatus"
                    ></el-progress>
                    <span>{{ scope.row.progressText }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button type="primary" link @click="viewPlanDetail(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>

      <!-- 右侧审核列表和快速功能 -->
      <el-col :span="8">
        <!-- 快速功能入口 -->
        <div class="quick-functions-card">
          <div class="card-header">
            <div class="card-title">
              <i class="fa fa-bolt"></i>
              <span>生产功能</span>
            </div>
          </div>
          <div class="card-body">
            <div class="functions-grid">
              <div class="function-item" v-for="(func, index) in quickFunctions" :key="index" @click="navigateTo(func.path)">
                <div class="function-icon" :style="{ backgroundColor: func.color }">
                  <i :class="func.icon"></i>
                </div>
                <div class="function-name">{{ func.name }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 生产计划待审核列表 -->
        <div class="pending-approval-card">
          <div class="card-header">
            <div class="card-title">
              <i class="fa fa-hourglass-half"></i>
              <span>待审核计划 ({{ pendingApprovalPlans.length }})</span>
            </div>
            <div class="card-tools">
              <el-button type="primary" link @click="viewAllPendingPlans">查看全部</el-button>
            </div>
          </div>
          <div class="card-body">
            <el-empty v-if="pendingApprovalPlans.length === 0" description="暂无待审核计划"></el-empty>
            <div v-else class="pending-list">
              <div 
                v-for="(plan, index) in pendingApprovalPlans" 
                :key="index" 
                class="pending-item"
                :class="{ 'border-bottom': index !== pendingApprovalPlans.length - 1 }"
              >
                <div class="pending-item-main">
                  <div class="pending-item-title">{{ plan.planNo }} - {{ plan.productName }}</div>
                  <div class="pending-item-info">
                    <div class="pending-item-quantity">
                      <span class="label">计划数量:</span> {{ plan.planQuantity }}
                    </div>
                    <div class="pending-item-date">
                      <span class="label">创建时间:</span> {{ plan.createTime }}
                    </div>
                  </div>
                </div>
                <div class="pending-item-actions">
                  <el-button-group>
                    <el-button type="success" size="small" @click="approvePlan(plan)">批准</el-button>
                    <el-button type="danger" size="small" @click="rejectPlan(plan)">拒绝</el-button>
                  </el-button-group>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 物料待补充提醒 -->
        <div class="material-alert-card">
          <div class="card-header">
            <div class="card-title">
              <i class="fa fa-exclamation-triangle"></i>
              <span>物料提醒</span>
            </div>
          </div>
          <div class="card-body">
            <el-empty v-if="materialAlerts.length === 0" description="暂无物料提醒"></el-empty>
            <div v-else class="alert-list">
              <el-alert
                v-for="(alert, index) in materialAlerts"
                :key="index"
                :title="alert.title"
                :description="alert.description"
                :type="alert.type"
                show-icon
                :closable="false"
                class="material-alert-item"
              >
                <template #default>
                  <el-button type="primary" link size="small" @click="handleMaterialAlert(alert)">
                    处理
                  </el-button>
                </template>
              </el-alert>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox } from 'element-plus'

export default defineComponent({
  name: 'ProductionHome',
  setup() {
    const router = useRouter()
    
    // 关键指标数据
    const kpiCards = ref([
      {
        title: '本月生产量',
        value: '1,682',
        trend: '+12.5%',
        trendIcon: 'fa fa-arrow-up',
        trendClass: 'trend-up',
        desc: '较上月',
        icon: 'fa fa-industry',
        class: 'blue-card'
      },
      {
        title: '生产计划完成率',
        value: '89%',
        trend: '+2.1%',
        trendIcon: 'fa fa-arrow-up',
        trendClass: 'trend-up',
        desc: '较上月',
        icon: 'fa fa-calendar-check-o',
        class: 'green-card'
      },
      {
        title: '生产成本',
        value: '￥463,250',
        trend: '-5.3%',
        trendIcon: 'fa fa-arrow-down',
        trendClass: 'trend-down',
        desc: '较上月',
        icon: 'fa fa-money',
        class: 'orange-card'
      },
      {
        title: '设备利用率',
        value: '78%',
        trend: '+3.8%',
        trendIcon: 'fa fa-arrow-up',
        trendClass: 'trend-up',
        desc: '较上月',
        icon: 'fa fa-cogs',
        class: 'purple-card'
      }
    ])
    
    // 趋势图表周期
    const trendChartPeriod = ref('month')
    
    // 生产计划进度过滤
    const progressFilter = ref('all')
    
    // 生产计划列表
    const productionPlans = ref([
      {
        planNo: 'PP202403001',
        productName: '高级办公椅 A103',
        planQuantity: 500,
        completedQuantity: 350,
        deadlineDate: '2024-04-10',
        progressPercentage: 70,
        progressStatus: 'success',
        progressText: '进行中，预计按时完成'
      },
      {
        planNo: 'PP202403002',
        productName: '会议桌 MT205',
        planQuantity: 200,
        completedQuantity: 180,
        deadlineDate: '2024-03-28',
        progressPercentage: 90,
        progressStatus: 'success',
        progressText: '进行中，预计提前完成'
      },
      {
        planNo: 'PP202403003',
        productName: '文件柜 FC310',
        planQuantity: 300,
        completedQuantity: 150,
        deadlineDate: '2024-04-05',
        progressPercentage: 50,
        progressStatus: 'warning',
        progressText: '进行中，存在延迟风险'
      },
      {
        planNo: 'PP202403004',
        productName: '员工工作站 WS501',
        planQuantity: 100,
        completedQuantity: 25,
        deadlineDate: '2024-04-15',
        progressPercentage: 25,
        progressStatus: 'exception',
        progressText: '进度落后，需要加快生产'
      },
      {
        planNo: 'PP202403005',
        productName: '折叠桌 FT105',
        planQuantity: 400,
        completedQuantity: 400,
        deadlineDate: '2024-03-20',
        progressPercentage: 100,
        progressStatus: 'success',
        progressText: '已完成'
      }
    ])
    
    // 待审核生产计划
    const pendingApprovalPlans = ref([
      {
        planNo: 'PP202403006',
        productName: '办公沙发 SF220',
        planQuantity: 150,
        createTime: '2024-03-26 09:15'
      },
      {
        planNo: 'PP202403007',
        productName: '会议椅 MC108',
        planQuantity: 300,
        createTime: '2024-03-26 10:42'
      },
      {
        planNo: 'PP202403008',
        productName: '书柜 BC330',
        planQuantity: 100,
        createTime: '2024-03-26 14:23'
      }
    ])
    
    // 物料提醒
    const materialAlerts = ref([
      {
        id: 1,
        title: '材料库存不足',
        description: '木板 M1025 库存低于安全库存量，当前库存: 230块，安全库存: 500块',
        type: 'warning' as 'warning'
      },
      {
        id: 2,
        title: '紧急材料需求',
        description: '金属脚架 F302 库存即将耗尽，当前库存: 56个，预计3天内用完',
        type: 'error' as 'error'
      }
    ])
    
    // 快速功能入口
    const quickFunctions = ref([
      { name: '生产计划', path: '/yxerp/production/plan', icon: 'fa fa-calendar', color: '#409EFF' },
      { name: 'BOM清单', path: '/yxerp/production/bom', icon: 'fa fa-list', color: '#67C23A' },
      { name: '生产单', path: '/yxerp/production/order', icon: 'fa fa-file-text', color: '#E6A23C' },
      { name: '领料单', path: '/yxerp/production/material', icon: 'fa fa-cube', color: '#F56C6C' },
      { name: 'MRP计算', path: '/yxerp/production/mrp', icon: 'fa fa-calculator', color: '#909399' },
      { name: '委外加工', path: '/yxerp/production/outsource', icon: 'fa fa-building', color: '#9966FF' },
      { name: '质量检验', path: '/yxerp/production/inspection', icon: 'fa fa-check-square', color: '#19BE6B' },
      { name: '生产成本', path: '/yxerp/production/cost', icon: 'fa fa-money', color: '#FF9900' }
    ])
    
    // 图表实例
    let productionSalesChart: echarts.ECharts | null = null
    
    // 创建生产量与销售趋势图
    const initTrendChart = () => {
      if (!document.getElementById('productionSalesTrend')) return
      
      productionSalesChart = echarts.init(document.getElementById('productionSalesTrend'))
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        legend: {
          data: ['生产量', '计划产量', '销售量', '销售目标'],
          right: 10,
          top: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: [
          {
            type: 'value',
            name: '数量',
            axisLabel: { formatter: '{value} 件' }
          }
        ],
        series: [
          {
            name: '生产量',
            type: 'bar',
            barWidth: 10,
            data: [350, 420, 460, 520, 490, 550, 580, 610, 590, 620, 650, 590],
            color: '#409EFF',
            emphasis: {
              focus: 'series'
            }
          },
          {
            name: '计划产量',
            type: 'line',
            symbol: 'emptyCircle',
            symbolSize: 8,
            data: [400, 450, 480, 500, 520, 550, 600, 620, 650, 680, 700, 650],
            color: '#67C23A',
            emphasis: {
              focus: 'series'
            }
          },
          {
            name: '销售量',
            type: 'bar',
            barWidth: 10,
            data: [320, 380, 450, 530, 470, 520, 550, 590, 580, 600, 630, 580],
            color: '#E6A23C',
            emphasis: {
              focus: 'series'
            }
          },
          {
            name: '销售目标',
            type: 'line',
            symbol: 'emptyCircle',
            symbolSize: 8,
            data: [380, 400, 450, 480, 500, 520, 550, 570, 600, 630, 650, 600],
            color: '#F56C6C',
            emphasis: {
              focus: 'series'
            }
          }
        ]
      }
      
      productionSalesChart.setOption(option)
    }
    
    // 监听窗口大小变化，调整图表大小
    const handleResize = () => {
      productionSalesChart?.resize()
    }
    
    // 页面挂载时初始化图表
    onMounted(() => {
      initTrendChart()
      window.addEventListener('resize', handleResize)
    })
    
    // 组件销毁前清除事件监听
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize)
      productionSalesChart?.dispose()
    })
    
    // 导航到指定路径
    const navigateTo = (path: string) => {
      router.push(path)
    }
    
    // 创建新生产计划
    const createProductionPlan = () => {
      navigateTo('/yxerp/production/plan/add')
    }
    
    // 查看生产计划详情
    const viewPlanDetail = (plan: any) => {
      navigateTo(`/yxerp/production/plan?planNo=${plan.planNo}`)
    }
    
    // 查看所有待审核计划
    const viewAllPendingPlans = () => {
      navigateTo('/yxerp/production/plan?status=pending')
    }
    
    // 审批生产计划
    const approvePlan = (plan: any) => {
      ElMessageBox.confirm(
        `确定批准生产计划 ${plan.planNo} ?`,
        '确认信息',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }
      ).then(() => {
        // 实际项目中应该调用API更新计划状态
        pendingApprovalPlans.value = pendingApprovalPlans.value.filter(p => p.planNo !== plan.planNo)
        ElMessage.success(`已批准生产计划 ${plan.planNo}`)
      }).catch(() => {})
    }
    
    // 拒绝生产计划
    const rejectPlan = (plan: any) => {
      ElMessageBox.confirm(
        `确定拒绝生产计划 ${plan.planNo} ?`,
        '确认信息',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 实际项目中应该调用API更新计划状态
        pendingApprovalPlans.value = pendingApprovalPlans.value.filter(p => p.planNo !== plan.planNo)
        ElMessage.success(`已拒绝生产计划 ${plan.planNo}`)
      }).catch(() => {})
    }
    
    // 处理物料提醒
    const handleMaterialAlert = (alert: any) => {
      navigateTo('/yxerp/purchase/order/add')
    }
    
    return {
      kpiCards,
      trendChartPeriod,
      progressFilter,
      productionPlans,
      pendingApprovalPlans,
      materialAlerts,
      quickFunctions,
      navigateTo,
      createProductionPlan,
      viewPlanDetail,
      viewAllPendingPlans,
      approvePlan,
      rejectPlan,
      handleMaterialAlert
    }
  }
})
</script>

<style scoped lang="scss">
.production-home-container {
  padding: 15px;
  background-color: #f5f7fa;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    .title {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 500;
      color: #303133;
      
      i {
        margin-right: 8px;
        font-size: 24px;
        color: #409EFF;
      }
    }
  }
  
  .kpi-cards {
    margin-bottom: 15px;
    
    .kpi-card {
      display: flex;
      padding: 15px;
      border-radius: 8px;
      background-color: white;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      
      &.blue-card .kpi-card-icon {
        background-color: #ecf5ff;
        color: #409EFF;
      }
      
      &.green-card .kpi-card-icon {
        background-color: #f0f9eb;
        color: #67C23A;
      }
      
      &.orange-card .kpi-card-icon {
        background-color: #fdf6ec;
        color: #E6A23C;
      }
      
      &.purple-card .kpi-card-icon {
        background-color: #f5f0ff;
        color: #9966FF;
      }
      
      .kpi-card-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 60px;
        height: 60px;
        border-radius: 8px;
        font-size: 24px;
        margin-right: 15px;
      }
      
      .kpi-card-content {
        flex: 1;
        
        .kpi-card-title {
          font-size: 14px;
          color: #909399;
          margin-bottom: 5px;
        }
        
        .kpi-card-value {
          font-size: 24px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 5px;
        }
        
        .kpi-card-trend {
          font-size: 12px;
          
          .trend-up {
            color: #67C23A;
          }
          
          .trend-down {
            color: #F56C6C;
          }
          
          .kpi-card-desc {
            color: #909399;
            margin-left: 8px;
          }
        }
      }
    }
  }
  
  .main-content {
    .chart-card,
    .plan-progress-card,
    .quick-functions-card,
    .pending-approval-card,
    .material-alert-card {
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      margin-bottom: 15px;
      overflow: hidden;
    }
    
    .chart-header,
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      border-bottom: 1px solid #ebeef5;
      
      .chart-title,
      .card-title {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        
        i {
          margin-right: 8px;
          color: #409EFF;
        }
      }
    }
    
    .chart-body,
    .card-body {
      padding: 15px;
    }
    
    .progress-info {
      display: flex;
      flex-direction: column;
      
      span {
        margin-top: 5px;
        font-size: 12px;
        color: #909399;
      }
    }
    
    .functions-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 15px;
      
      .function-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-3px);
        }
        
        .function-icon {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50px;
          height: 50px;
          border-radius: 8px;
          color: white;
          font-size: 20px;
          margin-bottom: 8px;
        }
        
        .function-name {
          font-size: 12px;
          color: #606266;
          text-align: center;
        }
      }
    }
    
    .pending-list {
      .pending-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        
        &.border-bottom {
          border-bottom: 1px solid #ebeef5;
        }
        
        .pending-item-main {
          flex: 1;
          
          .pending-item-title {
            font-size: 14px;
            font-weight: 500;
            color: #303133;
            margin-bottom: 8px;
          }
          
          .pending-item-info {
            display: flex;
            font-size: 12px;
            color: #909399;
            
            .pending-item-quantity {
              margin-right: 15px;
            }
            
            .label {
              color: #606266;
            }
          }
        }
      }
    }
    
    .material-alert-item {
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style> 